package com.mars.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mars.beans.LogType;
import com.mars.common.RequestHolder;
import com.mars.dao.SysLogMapper;
import com.mars.dao.SysRoleUserMapper;
import com.mars.dao.SysUserMapper;
import com.mars.pojo.SysLogWithBLOBs;
import com.mars.pojo.SysRoleUser;
import com.mars.pojo.SysUser;
import com.mars.util.IpUtil;
import com.mars.util.JsonMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author MARS
 * @date 2018/2/8
 */
@Service
public class SysRoleUserService {
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogMapper sysLogMapper;

    // 通过角色id获取userIds
    public List<SysUser> getListByRoleId(int roleId) {
        List<Integer> userIdList = sysRoleUserMapper.getUserIdListByRoleId(roleId);
        if (CollectionUtils.isEmpty(userIdList)) {
            return Lists.newArrayList();
        }
        // 如果不为空，通过用户id，从数据库中取出用户列表
        return sysUserMapper.getByIdList(userIdList);
    }

    public void changeRoleUsers(int roleId , List<Integer> userIdList) {
        // 与原始数据校验
        // 根据角色获取 之前 分配的用户id
        List<Integer> originUserIdList = sysRoleUserMapper.getUserIdListByRoleId(roleId);
        // 判断原有的用户id 和 传入的用户id是否一致
        // 判断长度是否相等
        if (originUserIdList.size() == userIdList.size()) {
            Set<Integer> originUserIdSet = Sets.newHashSet(originUserIdList);
            Set<Integer> userIdSet = Sets.newHashSet(userIdList);
            // 原有id中移除现有的，如果老的移除后结果为空，则表示传入的和已分配的保持一致
            originUserIdSet.removeAll(userIdSet);
            if (CollectionUtils.isEmpty(originUserIdSet)) {
                return ;
            }
        }
        // 更新操作
        updateRoleUsers(roleId,userIdList);
        saveRoleUserLog(roleId,originUserIdList,userIdList);
    }

    @Transactional
    private void updateRoleUsers(int roleId,List<Integer> userIdList) {
        // 先删除
        sysRoleUserMapper.deleteByRoleId(roleId);
        if (CollectionUtils.isEmpty(userIdList)) {
            return ;
        }
        // 批量插入
        List<SysRoleUser> roleUserList = Lists.newArrayList();
        // 遍历
        for (Integer userId : userIdList) {
            SysRoleUser sysRoleUser = SysRoleUser.builder().roleId(roleId).userId(userId).operator(RequestHolder.getCurrentUser().getUsername())
                    .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest())).operateTime(new Date()).build();

            roleUserList.add(sysRoleUser);
        }

        sysRoleUserMapper.batchInsert(roleUserList);

    }

    private void saveRoleUserLog(int roleId, List<Integer> before,List<Integer> after) {
        SysLogWithBLOBs sysLog = new SysLogWithBLOBs();
        sysLog.setType(LogType.TYPE_ROLE_USER);
        // tartgetId不能为空
        sysLog.setTargetId(roleId);
        sysLog.setOldValue(before == null ? "" : JsonMapper.obj2String(before));
        sysLog.setNewValue(after == null ? "" : JsonMapper.obj2String(after));
        sysLog.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysLog.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysLog.setOperateTime(new Date());
        sysLog.setStatus(1); // 没有复原过

        sysLogMapper.insertSelective(sysLog);
    }
}
